import 'package:enough_mail/enough_mail.dart';
import 'package:enough_mail_html/enough_mail_html.dart';
import 'package:flutter/material.dart';
import 'email_detail_page.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'email_model.dart';
import 'email_service.dart';
import 'email_login_page.dart';

class EmailListPage extends StatefulWidget {
  const EmailListPage({super.key});

  @override
  State<EmailListPage> createState() => _EmailListPageState();
}

class _EmailListPageState extends State<EmailListPage> {
  final List<Email> _emails = [];
  bool _isLoading = false;
  bool _hasError = false;
  String? _errorMessage;
  int _currentPage = 1;
  final ScrollController _scrollController = ScrollController();
  bool _hasMoreEmails = true;

  @override
  void initState() {
    super.initState();
    _loadEmails();
    _scrollController.addListener(_scrollListener);
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      if (!_isLoading && _hasMoreEmails) {
        _loadMoreEmails();
      }
    }
  }

  Future<void> _loadEmails() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
      _hasError = false;
      _errorMessage = null;
    });

    try {
      final emails = await EmailService.fetchEmails(page: 1);
      setState(() {
        _emails.clear();
        _emails.addAll(emails);
        _currentPage = 1;
        _hasMoreEmails = emails.length >= 20;
      });
    } catch (e) {
      setState(() {
        _hasError = true;
        _errorMessage = '加载邮件失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _loadMoreEmails() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    try {
      final nextPage = _currentPage + 1;
      final moreEmails = await EmailService.fetchEmails(page: nextPage);

      setState(() {
        _emails.addAll(moreEmails);
        _currentPage = nextPage;
        _hasMoreEmails = moreEmails.length >= 20;
      });
    } catch (e) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('加载更多邮件失败: $e')));
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  String generateHtml(MimeMessage mimeMessage) {
    return mimeMessage.transformToHtml(
      blockExternalImages: false,
      emptyMessageText: 'Nothing here, move on!',
    );
  }

  Future<void> _refreshEmails() {
    return _loadEmails();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('邮件列表'),
        backgroundColor: Theme.of(context).colorScheme.primary,
        foregroundColor: Theme.of(context).colorScheme.onPrimary,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              // 实现搜索功能
            },
          ),
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _isLoading ? null : _refreshEmails,
          ),
          PopupMenuButton<String>(
            onSelected: (value) {
              if (value == 'logout') {
                _logout();
              }
            },
            itemBuilder:
                (context) => [
                  const PopupMenuItem<String>(
                    value: 'logout',
                    child: Text('退出登录'),
                  ),
                ],
          ),
        ],
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    if (_hasError) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(Icons.error_outline, size: 48, color: Colors.red),
            const SizedBox(height: 16),
            Text(_errorMessage ?? '加载邮件时出错'),
            const SizedBox(height: 16),
            ElevatedButton(onPressed: _loadEmails, child: const Text('重试')),
          ],
        ),
      );
    }

    if (_emails.isEmpty) {
      if (_isLoading) {
        return const Center(child: CircularProgressIndicator());
      }
      return const Center(child: Text('没有邮件'));
    }

    return RefreshIndicator(
      onRefresh: _refreshEmails,
      child: ListView.builder(
        controller: _scrollController,
        itemCount: _emails.length + (_isLoading && _hasMoreEmails ? 1 : 0),
        itemBuilder: (context, index) {
          if (index == _emails.length) {
            return const Center(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: CircularProgressIndicator(),
              ),
            );
          }

          final email = _emails[index];
          return _buildEmailItem(email);
        },
      ),
    );
  }

  Widget _buildEmailItem(Email email) {
    final dateFormat = DateFormat('MM-dd HH:mm');
    final formattedDate = dateFormat.format(email.date);

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor:
              email.isRead
                  ? Colors.grey.shade200
                  : Theme.of(context).colorScheme.primary,
          child: Text(
            email.sender,
            style: TextStyle(
              color:
                  email.isRead
                      ? Colors.grey.shade700
                      : Theme.of(context).colorScheme.onPrimary,
            ),
          ),
        ),
        title: Text(
          email.subject,
          style: TextStyle(
            fontWeight: email.isRead ? FontWeight.normal : FontWeight.bold,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(email.sender, maxLines: 1, overflow: TextOverflow.ellipsis),
            Text(
              email.body,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.grey.shade600),
            ),
          ],
        ),
        trailing: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              formattedDate,
              style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
            ),
            const SizedBox(height: 4),
            if (email.attachments != null)
              const Icon(Icons.attachment, size: 16, color: Colors.grey),
          ],
        ),
        onTap: () async {
          // 导航到邮件详情页面
          final result = await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => EmailDetailPage(email: email),
            ),
          );

          // 如果邮件被删除，刷新列表
          if (result == true) {
            _refreshEmails();
          }
        },
        isThreeLine: true,
      ),
    );
  }

  Future<void> _logout() async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('退出登录'),
            content: const Text('确定要退出登录吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: const Text('确定'),
              ),
            ],
          ),
    );

    if (confirmed == true) {
      // 清除保存的密码
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove('password');

      if (!mounted) return;

      // 导航到登录页面
      Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => const EmailLoginPage()),
        (route) => false,
      );
    }
  }
}
